<?php
//服务
namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

use App\Models\User;
use App\Models\WeixinUser;
use App\Models\Order;
use App\Models\OrderShare;
use App\Models\Card;

use App\Tools\MoneyChange;

class ChargeController extends Controller
{

    //生成充值订单（普通充值）
    public function addOrder(Request $request) {
        if(!$request->token){//auth验证
            if(!Auth::id())
            {
                return  show('201','请登录后再充值');
            }
            $user_id = Auth::id();
        }else{//token验证
            $WeixinUser = WeixinUser::where('token',$request->token)->first();
            if(!$WeixinUser){
                return show("203","无效token！");
            }else{
                $user= User::find($WeixinUser->user_id);
                if(!$user){
                    return show("203","用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }
        //判断传入参数是否空
        if(!$request->money){
            return  show('202','充值金额不存在');
        }
        //判断是否为数字
        if(!is_numeric($request->money)){
            return  show('202','充值金额必须为数字');
        }
        //判断充值金额是否大于10元
        if($request->money<10){
            return show('202','充值金额不能小于10元');
        }
        //检测是否已存在未支付的充值订单
        $charge_order = Order::where('user_id',$user_id)
                             ->where('order_amount',$request->money)
                             ->where('order_type',5)
                             ->where('shop_id',-1)
                             ->where('order_status',1)
                             ->first();
        try{
            if(!$charge_order){
                //生成订单
                $insert=Order::create([
                    "user_id"=>$user_id,      //用户id
                    "shop_id"=>-1,     //商铺id(平台)
                    "order_type"=>5,            //充值
                    "order_number"=>randID(),   //订单编号
                    "order_status"=>1,          //订单状态
                    "note"=>'掌里通充值',        //订单备注
                    "order_price"=>$request->money,        //订单总价
                    "order_amount"=>$request->money,       //实际价格
                    "product_type"=>2,                     //充值模块（2）
                ]);
                return show("200","下单成功",["order_id"=>$insert['id'],"money"=>$request->money,"order_type"=>5]);
            }
            return show("200","下单成功",["order_id"=>$charge_order->id,"money"=>$request->money,"order_type"=>5]);
        }catch (\Exception $e){
            dd($e->getMessage());
        }

    }

    //充值卡充值
    public function cardCharge(Request $request){
        if(!Auth::id()){
            return  show('201','请登录后再充值');
        }
        $user_id = Auth::id();
        $rules = [
            'number'=>'required|exists:cards,number',
            'password'=>'required|integer|exists:cards,password'
        ];
        $message = [
            'number.*' =>'无效充值卡',
            'password.*' => '密码错误'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $card = card::where('number',$request->number)
                    ->where('password',$request->password)
                    ->where('user_id','=',null)
                    ->first();
        //卡不存在
        if(!$card){
            return show(201,'无效充值卡');
        }
        //卡已过期
        if(strtotime($card->over_time)<time()){
            return show(201,'无效充值卡');
        }
        //开始充值
        $moneychange = new MoneyChange();
        $moneychange->add_money($user_id,$card->amount,1,'充值卡充值，卡号：'.$card->number,0);
        //更新卡号
        $card->user_id = $user_id;
        $card->save();
        return show(200,'充值成功');
    }


    //在线优惠卡充值(带分享功能)
    public function getShareCards(){
         return show(200,'获取成功',config('Text')['shareCards']);
    }
    //生成优惠卡订单
    public function shareCard(Request $request){
        if(!$request->token){//auth验证
            if(!Auth::id())
            {
                return  show('201','请登录后再充值');
            }
            $user_id = Auth::id();
        }else{//token验证
            $WeixinUser = WeixinUser::where('token',$request->token)->first();
            if(!$WeixinUser){
                return show(201,"无效token！");
            }else{
                $user= User::find($WeixinUser->user_id);
                if(!$user){
                    return show(201,"用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }
        $rules = [
            'money'=>'required|integer',
        ];
        $message = [
            'money.*' =>'请输入要充值的金额',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }else{
            $amount = false;
            $sharecard = config('Text')['shareCards'];
            foreach($sharecard as $v){
                 if($v['money']==$request->money){
                     $amount =  $v['amount'];
                 }
            }
            if(!$amount){
                return show(201,'优惠卡不存在');
            }
        }
//        $data = encrypt(18819470586);
//        return $data;
        //检测是否已存在已支付的充值订单
        $charge_order = Order::where('user_id',$user_id)
            ->where('order_amount',$request->money)
            ->where('order_type',6)
            ->where('shop_id',-1)
            ->where('order_status',4)
            ->first();
        if($charge_order){
            return show(201,'每个用户仅限充值一张该卡');
        }
        //检测是否已存在未支付的充值订单
        $charge_order = Order::where('user_id',$user_id)
            ->where('order_amount',$request->money)
            ->where('order_type',6)
            ->where('shop_id',-2)
            ->where('order_status',1)
            ->first();
        try{
            if(!$charge_order){
                //生成订单
                $insert=Order::create([
                    "user_id"=>$user_id,        //用户id
                    "shop_id"=>-1,              //商铺id(平台)
                    "order_type"=>6,            //优惠卡
                    "order_number"=>randID(),   //订单编号
                    "order_status"=>1,          //订单状态
                    "note"=>'掌里通充值',        //订单备注
                    "order_price"=>$amount,     //订单总价
                    "order_amount"=>$request->money,       //实际价格
                    "product_type"=>2,                     //充值模块（2）
                ]);
                //获取分享的人
                if($request->code){
                    $whoshare = User::where('mobile',decrypt($request->code))->first();
                    if($whoshare){
                        if($whoshare->id != $user_id){
                            OrderShare::create([
                                "order_id"=>$insert['id'],
                                "whoshare_id"=>$whoshare->id,
                                "user_id"=>$user_id
                            ]);
                        }
                    }
                }
                return show("200","下单成功",["order_id"=>$insert['id'],"money"=>$request->money,"order_type"=>5]);
            }
            return show("200","下单成功",["order_id"=>$charge_order->id,"money"=>$request->money,"order_type"=>5]);
        }catch (\Exception $e){
            return show(201,'不能充值,请联系客服！');
        }
    }


    //获取当前人的分享码
    public function getShareCode(){
        if(!Auth::id()){
            return show(201,"未登录");
        }
        $user=Auth::user();
        //验证手机号
        if(!preg_match("/^1[345678]{1}\d{9}$/",$user->mobile)){
            return show(202,"请先绑定手机号");
        }else{
            $code = encrypt($user->mobile);
        }
        return show(200,"获取推荐码成功",['code'=>$code]);
    }


}
